/**
 * - send ICMP ECHO_REQUEST to a host or device.
 * - send 3 pings at 1 sec intervals and get avg response.
 * - parameters and output format require 
 * - ping from Linux iputils or ping from MS Windows.
 */

import java.util.regex.*;

import br.edu.ufc.deti.util.Utils;

public class benchmark_rede{
    
    private String cmdLine;
    private String osName = System.getProperty("os.name");

    public benchmark_rede(String host) {
        // if we are running on Windows
        if (this.osName.contains("indows")) {
            this.cmdLine = "ping -n 60 " + host;  // do 60 pings
        }
        // if we are running on a system with iputils (Linux)
        else {
            this.cmdLine = "ping " + host + " -c 60";  // do 60 pings
        }
    }

	
    public double ping() {
        try {
            String cmdOutput = Utils.cmdExec(cmdLine);
            
            Pattern pattern;
            if (this.osName.contains("indows")) {
                pattern = Pattern.compile("Average = (.*)ms");  // get avg from ping output
            }
            else {
                pattern = Pattern.compile(" = (.*?)/(.*?)/");  // get avg from ping output
            }
            Matcher matcher = pattern.matcher(cmdOutput);
            matcher.find();
            
            double avg;
            if (this.osName.contains("indows")) {
                avg = Double.parseDouble(matcher.group(1));  // avg response time in millisecs
	        } 
            else {
                avg = Double.parseDouble(matcher.group(2));  // avg response time in millisecs
	        }
            
            return avg;            
        }
        catch (Exception ex) {
            System.err.println("ERROR - invalid response from system ping");
            ex.printStackTrace();
            return 00;
        }
    }
		
    public static void main(String[] args) {
        benchmark_rede p = new benchmark_rede("192.168.1.64");
        double respTime = p.ping();
        System.out.println(respTime);
    }
}
